package in.muton.edushare.pages;

import in.muton.edushare.EduShareSession;
import in.muton.edushare.auth.EduShareAuthenticatedPage;
import in.muton.edushare.auth.roles.PageRoleCheck;
import in.muton.edushare.auth.roles.UnivRoleCheck;
import in.muton.edushare.pages.cp.semCP.SemesterCP;
import in.muton.edushare.pages.user.UserCalendar;
import in.muton.edushare.pages.user.UserCourses;
import in.muton.edushare.pages.user.UserDept;
import in.muton.edushare.pages.user.UserPage;
import in.muton.edushare.pages.user.UserSettings;
import in.muton.edushare.pages.user.UserUniv;
import in.muton.edushare.url.EntityPageParams;
import in.muton.edushare.url.URLLoader;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.RestartResponseAtInterceptPageException;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.markup.html.CSSPackageResource;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.JavascriptPackageResource;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.model.CompoundPropertyModel;

import com.edushare.common.constants.URLConstants;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.AcademicYearModel;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.UserRoles;
import com.edushare.common.vo.Users;

/**
 * Base page for all the pages that need a footer and a header.
 * 
 * @author Naishe
 * 
 */
public abstract class EduShareBasePage extends EduShareAuthenticatedPage
		implements IHeaderContributor {

	private static final Log log = LogFactory.getLog(EduShareBasePage.class);

	public static final String HOMEPAGE = "homepage";
	public static final String PROFILEPAGE = "profilepage";
	public static final String PEOPLEPAGE = "peoplepage";
	public static final String DEPARTMENTPAGE = "deptpage";
	public static final String SETTINGSPAGE = "settingspage";
	public static final String CALENDARPAGE = "calendar";
	public static final String COURSESPAGE = "courses";
	public static final String ASSIGNMENTPAGE = "assignmentpage";
	public static final String PROGRAMPAGE = "programpage";
	protected PageRoleCheck prc;
	private static final long serialVersionUID = -6017590114838795962L;

	public EduShareBasePage() {
		super();
		add(CSSPackageResource.getHeaderContribution(EduShareBasePage.class,
				"home.css"));
		if (!EduShareSession.get().isLoggedIn()) {
			log.debug("Unauthaourized. Redirecting to login page.");
			setRedirect(true);
			throw new RestartResponseAtInterceptPageException(
					in.muton.edushare.pages.EduShareLogin.class);
		}

		setDefaultModel(new CompoundPropertyModel<EduShareBasePage>(this));
		add(new Label("pageTitle"));
		add(new Label("userAndRole"));
		// add(new Label("errorMessage").setEscapeModelStrings(false));
		add(new Link<String>("logout") {
			private static final long serialVersionUID = -782524135761788529L;

			@Override
			public void onClick() {
				EduShareSession.get().logOutUser();
				getSession().invalidate();
				setResponsePage(in.muton.edushare.pages.EduShareLogin.class);
			}
		});

		add(new BookmarkablePageLink<Void>("home", UserPage.class));
		add(new BookmarkablePageLink<Void>("calendar", UserCalendar.class));
		add(new BookmarkablePageLink<Void>("univ", UserUniv.class));
		add(new BookmarkablePageLink<Void>("dept", UserDept.class));
		add(new BookmarkablePageLink<Void>("course", UserCourses.class));
		add(new BookmarkablePageLink<Void>("settings", UserSettings.class));

		{
			Universities adminUniv = null;// local variable
			for (UserRoles u : getLoggedInUser().getRoleList()) {
				adminUniv = u.getUniversity();
				if (UnivRoleCheck.isAdmin(adminUniv, getLoggedInUser()))
					break;
				else
					adminUniv = null;
			}
			if (adminUniv != null)
				add(new BookmarkablePageLink<Void>("ctrlPanel",
						SemesterCP.class, EntityPageParams
								.getParams(new CayenneModel<Universities>(
										adminUniv))));
			else
				add(new EmptyPanel("ctrlPanel"));
		}

		add(CSSPackageResource.getHeaderContribution(EduShareBasePage.class,
				"home.css"));
		add(JavascriptPackageResource.getHeaderContribution(
				EduShareBasePage.class, "home.js"));
		if (EduShareSession.get().isLoggedIn()) {
			List<UserRoles> roles = getLoggedInUser().getRoleList();
			if (roles != null && roles.size() > 0) {
				String acadStr = "";
				if (roles.size() == 1) {
					Universities u = roles.get(0).getUniversity();
					int yr = u.getCurrentAcadYear();
					for (AcademicYearModel m : u.getAcademicYearModels()) {
						if (m.getIsCurrent() == AcademicYearModel.ACTIVE_SEM) {
							acadStr = acadStr + m.getSemesterName() + ", ";
							break;
						}
					}
					acadStr = acadStr + yr;
					add(new Label("semesterInfo", acadStr));
				} else {
					add(new EmptyPanel("semesterInfo"));
				}
			}
		}
		add(new FooterLinks("footerLinks"));
	}

	public String getUserAndRole() {
		String str = "";
		str = EduShareSession.get().getLoggedInUser().getCompleteUserName()
				+ getUserRole();
		return str;
	}

	private String errorMessage = "";

	public void clearError() {
		setErrorMessage("");
	}

	public abstract String getUserRole();

	public abstract String getPageTitle();

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;

	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public Users getLoggedInUser() {
		return getEduShareSession().getLoggedInUser();
	}

	public void renderHead(IHeaderResponse response) {
		String feedbackMessage = "";
		if (StringUtil.isValid(errorMessage)
				&& StringUtil.isValid(EduShareSession.get().getFeedbackMsg())) {
			feedbackMessage = errorMessage + "<br />"
					+ EduShareSession.get().getFeedbackMsg();
		} else if (StringUtil.isValid(errorMessage)) {
			feedbackMessage = errorMessage;
		} else if (StringUtil.isValid(EduShareSession.get().getFeedbackMsg())) {
			feedbackMessage = EduShareSession.get().getFeedbackMsg();
		}

		if (StringUtil.isValid(feedbackMessage))
			response
					.renderOnDomReadyJavascript("Edushare.FunctionalTextFields.SetError('"
							+ feedbackMessage + "')");
		errorMessage = "";
		EduShareSession.get().setFeedbackMsg("");

	}

	public void throwUnauthorisedException() {
		throw new RestartResponseException(URLLoader
				.getPageClass(URLConstants.UNAUTHORIZED_PATH));
	}

	public void throwPageNotFoundException() {
		throw new RestartResponseException(URLLoader
				.getPageClass(URLConstants.PAGE_NOT_FOUND_PATH));
	}
}
